package orm

import (
	"gitee.com/xiawucha365/sago.v2/core/config"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type DbMysql struct {
	Db
}

func NewDbMysql(cf *config.Config, engine ...DbEngineName) *DbMysql {
	dbmysql := &DbMysql{}
	key := DbEngineName(cf.Mysql.Engine)
	//设置优先
	if len(engine) > 0 && engine[0] != "" {
		if index, ok := orms[engine[0]]; ok {
			dbmysql.engineType = index
		}
		//配置
	} else if cf.Mysql.Engine != "" {
		if index, ok := orms[key]; ok {
			dbmysql.engineType = index
		}
	} else {
		panic("mysql-engine-未配置")
	}

	dbmysql.initMysqlDb(cf)
	return dbmysql
}

func (dbm *DbMysql) initMysqlDb(cf *config.Config) {
	switch dbm.engineType {
	case DbMysqlEngineTypeXorm:
		dbm.Engine.Xorm = newDbMysqlXormByConfig(cf)
	case DbMysqlEngineTypeGorm:
		dbm.Engine.Gorm = newDbMysqlGormByConfig(cf)
	default:
		dbm.Engine.Xorm = newDbMysqlXormByConfig(cf)
	}
}

func (dbm *DbMysql) Close()  error{
	switch dbm.engineType {
	case DbMysqlEngineTypeXorm:
		return dbm.Engine.Xorm.DB().Close()
	case DbMysqlEngineTypeGorm:
		return dbm.Engine.Gorm.DB.Close()
	default:
		return dbm.Engine.Xorm.DB().Close()
	}
}

func newDbMysqlXormByConfig(cf *config.Config) *EngineXorm {
	addr := cf.Mysql.Username + ":" + cf.Mysql.Password + "@tcp(" + cf.Mysql.Addr + ")/" + cf.Mysql.Dbname + "?charset=" +
		cf.Mysql.Charset + "&parseTime=True&loc=Local"
	return createXorm(addr)
}

func newDbMysqlGormByConfig(cf *config.Config) *EngineGorm {
	addr := cf.Mysql.Username + ":" + cf.Mysql.Password + "@tcp(" + cf.Mysql.Addr + ")/" + cf.Mysql.Dbname + "?charset=" +
		cf.Mysql.Charset + "&parseTime=True&loc=Local"
	return createGorm(addr)
}

//直接操作db
func GetMysqlConnByDb(cf *config.Config, engine DbEngineName, dbname string) *DbMysql {
	cf.Mysql.Dbname = dbname
	return NewDbMysql(cf, engine)
}

//通过addr链接
func GetMysqlConnByAddr(cf *config.Config, engine DbEngineName, addr string) *DbMysql {
	db := NewDbMysql(cf, engine)

	switch db.engineType {
	case DbMysqlEngineTypeXorm:
		db.Engine.Xorm = createXorm(addr)
	case DbMysqlEngineTypeGorm:
		db.Engine.Gorm = createGorm(addr)
	default:
		db.Engine.Xorm = createXorm(addr)
	}
	return db

}
